import Vue from 'vue'
import VueRouter from 'vue-router'
// 一级路由
import Detail from '@/components/Detail.vue'
import Layout from '@/components/Layout.vue'
import Login from '@/components/Login.vue'
import Register from '@/components/Register.vue'
// 二级路由
import Article from '@/components/Article.vue'
import Collect from '@/components/Collect.vue'
import Like from '@/components/Like.vue'
import User from '@/components/User.vue'
// import { get } from 'core-js/core/dict'

// 获取getToken方法
import { getToken } from '@/utils/local'

Vue.use(VueRouter)

const routes = [
  { path: '/detail/:id?', component: Detail },
  { path: '/register', component: Register },
  { path: '/login', component: Login },
  {
    path: '/',
    component: Layout,
    redirrct: '/article',
    children: [
      { path: 'article', component: Article },
      { path: 'collect', component: Collect },
      { path: 'like', component: Like },
      { path: 'user', component: User }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/register']

router.beforeEach((to, from, next) => {
  // to 要去哪（即将发的页面）
  // from 从哪来（从哪个页面跳转过来）
  // next是否放行（只能调用该函数 才会解析组件，看到内容渲染）
  // 拦截到某个页面 next(路径)
  // 封装的 getToken()组件
  const token = getToken()
  if (token) {
    // token存在 -> 放行
    next()
  } else {
    // console.log(to)
    // 没有token -> 不要直接拦截
    // 判断是或属于白名单路径
    // 1.属于白名单，直接放行
    // 2.不属于白名单，在进行拦截？？拦截到登录页
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
